<script setup lang="ts">
import { Search, TrashBinOutline } from '@vicons/ionicons5';
import { ref } from 'vue';
import type { DrawerPlacement, UploadFileInfo } from 'naive-ui';
import { NButton, useDialog, useMessage } from 'naive-ui';
import { useRouterPush } from '@/hooks/common/router';
import {
  deleteFileInfo,
  uploadDocumentFile,
  uploadOtherFile,
  uploadQualificationFile,
  uploadUserInfoFile
} from '@/service/api';

interface Props {
  thirdParentId?: number;
  thirdType?: number;
  fileData?: any[];
}

const props = withDefaults(defineProps<Props>(), {
  thirdParentId: 0,
  thirdType: 0,
  fileData: () => []
});

const active = ref(false);

const message = useMessage();
const dialog = useDialog();

const thirdName = ref({
  '2': '人员',
  '3': '案例',
  '4': '其他信息',
  '5': '标书'
});

const placement = ref<DrawerPlacement>('right');

const activate = (place: DrawerPlacement) => {
  active.value = true;
  placement.value = place;
};

const emit = defineEmits(['refresh']);

const fileList = ref([]);

// 上传文件变更
const handleChange = async (data: { file: UploadFileInfo; fileList: UploadFileInfo[] }) => {
  fileList.value = data.fileList;
};

const { VITE_OTHER_SERVICE_BASE_URL } = import.meta.env;

const otherUrl: any = JSON.parse(VITE_OTHER_SERVICE_BASE_URL);

const imgUrl = otherUrl.imgUrl;

const dataLoading = ref(false);

const btnLoading = ref(false);

const { routerPushByKey } = useRouterPush();

// 点击预览
function downloadFile(item: any) {
  const filePath = item.filePath;
  if (item.filePath.includes('.pdf')) {
    window.open(imgUrl + item.filePath);
  } else {
    routerPushByKey('bid-materials_materials', {
      query: {
        filePath
      }
    });
  }
  // let aLink = document.createElement("a");
  // aLink.style.display = "none";
  // aLink.href = imgUrl + item.filePath;
  // aLink.setAttribute("模版", new Date().getTime() + ".docx");
  // document.body.appendChild(aLink);
  // aLink.click();
  // document.body.removeChild(aLink);
  // message.success("下载成功");
}

function closeDrawer() {
  fileList.value = [];
}

// 上传
async function handleClick() {
  if (fileList.value.length === 0) {
    message.warning('请添加上传文件');
    return;
  }
  const formData = new FormData();
  fileList.value?.forEach((item: any) => {
    if (item.status === 'pending') {
      formData.append('files', item.file as Blob);
    }
  });
  formData.append('folderId', props.thirdParentId as any);
  dataLoading.value = true;
  btnLoading.value = true;
  // type为人员信息时
  if (props.thirdType === 2) {
    const { data, error } = await uploadUserInfoFile(formData);
    if (!error) {
      emit('refresh', props.thirdParentId, searchParams);
    }
    dataLoading.value = false;
    active.value = false;
    btnLoading.value = false;
  } // 案例信息
  else if (props.thirdType === 3) {
    const { data, error } = await uploadQualificationFile(formData);
    if (!error) {
      emit('refresh', props.thirdParentId, searchParams);
    }
    dataLoading.value = false;
    active.value = false;
    btnLoading.value = false;
  } // 其他信息
  else if (props.thirdType === 4) {
    const { data, error } = await uploadOtherFile(formData);
    if (!error) {
      emit('refresh', props.thirdParentId, searchParams);
    }
    dataLoading.value = false;
    active.value = false;
    btnLoading.value = false;
  } // 标书库
  else if (props.thirdType === 5) {
    const { data, error } = await uploadDocumentFile(formData);
    if (!error) {
      emit('refresh', props.thirdParentId, searchParams);
    }
    dataLoading.value = false;
    active.value = false;
    btnLoading.value = false;
  }
}
// 下载标书
function handleDownload() {
  if (props.fileData.length === 0) {
    message.info('没有可以下载的模版');
  } else {
    const aLink = document.createElement('a');
    aLink.style.display = 'none';
    if (props.thirdType === 2) {
      aLink.href = `${imgUrl}/profile/default/userinfo/人员信息-模板（样）.docx`;
    } else if (props.thirdType === 3) {
      aLink.href = `${imgUrl}/profile/default/qualification/案例信息-模板（样）.docx`;
    } else {
      aLink.href = imgUrl + props.fileData[0].filePath;
    }
    aLink.setAttribute('download', `案件导入模板_${new Date().getTime()}.docx`);
    document.body.appendChild(aLink);
    aLink.click();
    document.body.removeChild(aLink);
    message.success('下载成功');
  }
}

const searchParams = ref({
  fileCname: ''
});

// 搜索 切换标签条件
function handleSearch() {
  emit('refresh', props.thirdParentId, searchParams);
}

function handleDelete(item: any) {
  dialog.info({
    title: '删除标书',
    content: '请问是否确认删除该标书？',
    positiveText: '确定',
    negativeText: '返回',
    onPositiveClick: async () => {
      const { data, error } = await deleteFileInfo({ idList: item.id });
      if (!error) {
        message.success('已删除');
        emit('refresh', props.thirdParentId, searchParams);
      }
    },
    onNegativeClick: () => {
      message.warning('已取消');
    }
  });
}
</script>

<template>
  <div class="w-full">
    <div class="tips">
      <span v-if="thirdType != 4 && thirdType != 5">注：重新上传会覆盖原word</span>
    </div>
    <img
      v-if="thirdType != 4 && thirdType != 5"
      class="download"
      src="@/assets/bid-materials/download.png"
      alt=""
      @click="handleDownload"
    />
    <div v-if="thirdType == 5" class="search-box">
      <NInput
        v-model:value="searchParams.fileCname"
        placeholder="请输入文件名称"
        size="large"
        clearable
        @keyup.enter.native="handleSearch"
      >
        <template #suffix>
          <NButton text style="font-size: 24px" @click="handleSearch">
            <NIcon :component="Search" />
          </NButton>
        </template>
      </NInput>
    </div>
    <div class="files">
      <div class="file uploadFile" @click="activate('right')">
        <img class="uploadImg" src="@/assets/bid-materials/word-trans.png" alt="" />
        <div class="uploadFileName">
          <NButton class="w-200px font-size-16px" color="#FFFFFF" text-color="#333333" strong>
            上传
            <span>{{ thirdName[thirdType] }}</span>
          </NButton>
          <div class="notice">·支持扩展名 .docx</div>
        </div>
      </div>
      <div v-for="item in fileData" :key="item.id" class="file" @click="downloadFile(item)">
        <img class="typeImg" src="@/assets/bid-materials/word.png" alt="" />
        <div class="fileName">{{ item.fileCname }}</div>
        <NButton
          v-if="thirdType != 1 && item.more2 != 'system'"
          text
          style="font-size: 20px; font-weight: bold; position: absolute; color: #806cfe; top: 152px; right: 5px"
          @click.stop="handleDelete(item)"
        >
          <NIcon>
            <TrashBinOutline />
          </NIcon>
        </NButton>
      </div>
    </div>
  </div>
  <NDrawer v-model:show="active" :width="502" :placement="placement" :mask-closable="false">
    <NDrawerContent title="文件上传" closable>
      <template #header>文件上传</template>
      <NSpin :show="dataLoading">
        <NUpload
          multiple
          :default-upload="false"
          directory-dnd
          accept=".docx"
          :on-after-leave="closeDrawer()"
          :max="thirdType === 5 ? undefined : 1"
          @change="handleChange"
        >
          <NUploadDragger>
            <div style="margin-bottom: 12px; display: flex; justify-content: center">
              <img src="@/assets/bid-materials/word.png" alt="" width="68" height="67" />
            </div>
            <NText class="font-size-16px">点击或者拖动文件到该区域来上传</NText>
            <NP depth="3" class="mt-8px">·支持扩展名：.docx</NP>
          </NUploadDragger>
          <div v-if="thirdType !== 5" class="warn">注: 请自行检查上传内容与模板保持一致, 仅支持单个文件上传。</div>
        </NUpload>
      </NSpin>
      <template #footer>
        <NButton class="h-42px w-110px" type="primary" :loading="btnLoading" @click="handleClick">
          确 定
        </NButton>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped lang="scss">
.search-box {
  line-height: 50px;
  margin-top: 13px;
  margin-left: 32px;
  width: 464px;
}
.tips {
  margin-left: 20px;
  margin-top: 30px;
  font-weight: 400;
  font-size: 18px;
  color: #4501b7;
}
.download {
  float: right;
  margin-right: 79px;
  &:hover {
    cursor: pointer;
  }
}
.files {
  padding-top: 20px;
  width: 1583px;
  height: 600px;
  display: flex;
  flex-wrap: wrap;
  .file {
    width: 281px;
    height: 180px;
    border-radius: 12px;
    border: 1px solid #ebeef5;
    margin: 16px 16px;
    position: relative;
    &:hover {
      background: #f3f4f8;
      cursor: pointer;
    }
    .typeImg {
      position: absolute;
      top: 25px;
      left: 106px;
      width: 73px;
      height: 73px;
    }
    .fileName {
      text-align: center;
      width: 280px;
      padding: 0 30px;
      margin-top: 110px;
      font-weight: 400;
      font-size: 18px;
      color: #333333;
      display: -webkit-box;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: wrap;
      word-wrap: break-word;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2; /* 限制在3行 */
    }
  }
}

.warn {
  font-weight: 400;
  font-size: 16px;
  color: #4501b7;
  margin-top: 10px;
}
.uploadImg {
  position: absolute;
  top: 35px;
  left: 116px;
  width: 51px;
  height: 51px;
}
.uploadFile {
  background: #f3f4f8;
  .uploadFileName {
    text-align: center;
    width: 281px;
    padding: 0 30px;
    margin-top: 100px;
    font-weight: 400;
    font-size: 18px;
    color: #333333;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    line-clamp: 1; /* 这里的3表示最多显示2行 */
    overflow: hidden;
  }
  .notice {
    margin-top: 8px;
    font-weight: 900;
    font-size: 15px;
    color: #cccccc;
  }
}
</style>
